//
//  YPhotothumbnailsViewController.m
//  AXLPhotoBower
//
//  Created by gome on 2018/5/4.
//  Copyright © 2018年 gome. All rights reserved.
//

#import "JCPhotoCameraRollViewController.h"
#import "JCPhotoGlobalVar.h"
#import "JCPhotoPreviewViewController.h"

@interface JCPhotoCameraRollViewController ()
@property (strong,nonatomic) ALAssetsLibrary * assetsLibrary;

@property (strong,nonatomic) UICollectionView * collectionView;
@property (strong,nonatomic) UIToolbar * toolBar;
@property (assign,nonatomic) BOOL isMaxNum;
@property (strong,nonatomic) NSMutableDictionary * selectedFullScreenImages;
@property (strong,nonatomic) NSMutableArray * aLAssets;
@property (strong,nonatomic) UIBarButtonItem * selectBtn;
@property (strong,nonatomic) ALAssetRepresentation * representation;
@property (strong,nonatomic) JCPhotoGlobalVar * globalVar;

@property (nonatomic, strong) UIView *bottomBarView;
@property (strong, nonatomic) UIButton *uploadButton;
@property (strong, nonatomic) UIButton *previewButton;
@end

@implementation JCPhotoCameraRollViewController
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (NSString *)getZH_CN:(NSString *)name {
    if ([name isEqualToString:@"Favorites"]) {
        return @"个人收藏";
    }
    else if ([name isEqualToString:@"Panoramas"]) {
        return @"全景照片";
    }
    else if ([name isEqualToString:@"Camera Roll"]) {
        return @"相机胶卷";
    }
    else if ([name isEqualToString:@"Screenshots"]) {
        return @"屏幕快照";
    }
    else if ([name isEqualToString:@"Bursts"]) {
        return @"连拍快照";
    }
    else if ([name isEqualToString:@"Selfies"]) {
        return @"自拍";
    }
    else if ([name isEqualToString:@"Recently Added"]) {
        return @"最近添加";
    }
    else {
        return name;
    }
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cancel {
    _globalVar.currentNum = 0;
    _globalVar.indexPaths = nil;
    _globalVar.selectedThumbnails = nil;
    _globalVar.selectedImgs = nil;
    _globalVar.selectedAlassets = nil;
    _globalVar.reloadIndexPaths = nil;
    _globalVar.animation = nil;
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadNavgationBar {
    UIBarButtonItem * backItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    [backItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} forState:UIControlStateNormal];
    self.navigationItem.backBarButtonItem = backItem;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:15]} forState:UIControlStateNormal];
    
    self.title = [self getZH_CN:[_album valueForProperty:ALAssetsGroupPropertyName]];
    
    self.title = @"相机胶卷";

}

- (UIImage*)createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (void)addBottomBar {
    [self bottomBarView];
    [self uploadButton];
    [self previewButton];
}

 - (UIView *)bottomBarView {
    if (!_bottomBarView) {
        _bottomBarView = [[UIView alloc] init];
        [self.view addSubview:_bottomBarView];
        
        [_bottomBarView setFrame:CGRectMake(0, self.view.frame.size.height - 49, self.view.frame.size.width, 49)];
        [_bottomBarView setBackgroundColor:[UIColor grayColor]];
    }
    
    return _bottomBarView;
}

- (UIButton *)uploadButton {
    if (!_uploadButton) {
        _uploadButton = [[UIButton alloc] init];
        [self.bottomBarView addSubview:_uploadButton];
        [_uploadButton setTitle:@"上传" forState:UIControlStateNormal];
        [_uploadButton setBackgroundColor:[UIColor blueColor]];
        [_uploadButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [_uploadButton.layer setCornerRadius:4.0f];

        [_uploadButton setFrame:CGRectMake(self.view.frame.size.width - 74, 9, 60, 30)];
        
        [_uploadButton addTarget:self action:@selector(clickUploadButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _uploadButton;
}

- (void)clickUploadButton:(UIButton *)sender {
    [self doneTap];
}

- (void)doneTap {
    
    UIActivityIndicatorView * activityIV = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIV.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/3);
    [self.view addSubview:activityIV];
    [activityIV startAnimating];
    
    UIImage * fullScreenImg;
    
    for (int i = 0; i < _globalVar.selectedAlassets.count; i++) {
        _representation = [_globalVar.selectedAlassets[i] defaultRepresentation];
        
        fullScreenImg = [UIImage imageWithCGImage:[_representation fullScreenImage]] ;
        fullScreenImg = [self compressionImage:fullScreenImg WithScale:_globalVar.targetImageScale];
        
        [_globalVar.selectedImgs addObject:fullScreenImg];
        
        UIImage * thumbnail = [UIImage imageWithCGImage:((ALAsset *)_globalVar.selectedAlassets[i]).thumbnail];
        [_globalVar.selectedThumbnails addObject:thumbnail];
    }
    
    _globalVar.indexPaths = nil;
    _globalVar.reloadIndexPaths = nil;
    _globalVar.selectedAlassets = nil;
    _globalVar.animation = nil;
    
    [activityIV stopAnimating];
    [activityIV removeFromSuperview];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (UIButton *)previewButton {
    if (!_previewButton) {
        _previewButton = [[UIButton alloc] init];
        [self.bottomBarView addSubview:_previewButton];
        [_previewButton setTitle:@"预览" forState:UIControlStateNormal];
        [_previewButton setBackgroundColor:[UIColor blueColor]];
        [_previewButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [_previewButton.layer setCornerRadius:4.0f];
        
        [_previewButton setFrame:CGRectMake(14, 9, 60, 30)];
        
        [_previewButton addTarget:self action:@selector(clickPreviewButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _uploadButton;
}

- (void)clickPreviewButton:(UIButton *)sender {
    [self presentTap];
}

- (void)presentTap {
    if (_globalVar.currentNum <= 0) {
        return;
    }
    
    UIImage * centerImage = [UIImage imageWithCGImage:[_globalVar.selectedAlassets[0] thumbnail]] ;
    JCPhotoPreviewViewController * previewVC = [JCPhotoPreviewViewController new];
    previewVC.centerImage = centerImage;
    NSIndexPath * indepath = [NSIndexPath indexPathForRow:0 inSection:1];
    previewVC.indexPath = indepath;
    previewVC.aLAssets = _globalVar.selectedAlassets;
    previewVC.lib = _lib;
    previewVC.isPresent = YES;
    [self.navigationController pushViewController:previewVC animated:YES];
}



- (void)loadCollectionView {
    
    UICollectionViewFlowLayout * pickImageCollectionLayout =  [UICollectionViewFlowLayout new];
    pickImageCollectionLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    pickImageCollectionLayout.minimumInteritemSpacing = 2;
    pickImageCollectionLayout.minimumLineSpacing = 2;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 44) collectionViewLayout:pickImageCollectionLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[JCPhotoCollectionViewCell class] forCellWithReuseIdentifier:@"JCPhotoCollectionViewCell"];
    [self.view addSubview:_collectionView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    _globalVar = [JCPhotoGlobalVar shareGlobalVar];
    
    [self loadNavgationBar];
    [self loadAlbum];
    [self loadCollectionView];
    [self addBottomBar];
}

- (void)loadAlbum {
    // 获取当前应用对照片的访问授权状态
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    // 如果没有获取访问授权，或者访问授权状态已经被明确禁止，则显示提示语，引导用户开启授权
    if (status == ALAuthorizationStatusRestricted || status == ALAuthorizationStatusDenied) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"应用想访问您的相册" message:@"请设置应用的相册访问权限" delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"去设置", nil];
        [alert show];
    }
    else {
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
        _aLAssets = [NSMutableArray array];

        [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            if (group) {
                if (group.numberOfAssets > 0) {
                    
                    if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"Camera Roll"]) {
//                        title 相机交卷
                        self.album = group;
                        self.lib = self->_assetsLibrary;
                        
                        [self->_album enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                            if (result) {
                                [self->_aLAssets addObject:result];
                            }
                        }];

                        [self.collectionView reloadData];
                    }
                }
            }
            else {

            }
        }  failureBlock:^(NSError *error) {
            NSLog(@"Asset group not found!");
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    if ( _globalVar.reloadIndexPaths.count > 0) {
        [_collectionView reloadItemsAtIndexPaths:_globalVar.reloadIndexPaths];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (_globalVar.selectedAlassets.count > 0) {
        _selectBtn.enabled = YES;
        
        
        [_uploadButton setTitle:[NSString stringWithFormat:@"上传(%d)",_globalVar.currentNum] forState:UIControlStateNormal];
    } else {
        _selectBtn.enabled = NO;
    }
}

- (UIImage *)compressionImage:(UIImage *)image WithScale:(CGFloat)scale {
    /* 按给定尺寸 按比例缩放的方法
    实现等比例缩放
    double hfactor = image.size.width / targetSize.width;
    double vfactor = image.size.height / targetSize.height;
    double factor = fmax(hfactor, vfactor);
    绘制画布
    double newWith = image.size.width / factor;
    double newHeight = image.size.height / factor;
    CGSize newSize = CGSizeMake(newWith, newHeight);
    */
    /*
     按照给定缩放比例缩放
     */
    double newWith = image.size.width * scale;
    double newHeight = image.size.height * scale;
    CGSize newSize = CGSizeMake(newWith, newHeight);
  
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newWith, newHeight)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //按照jpg格式进行了压缩,如果需要png格式就把这个换成 : UIImagePNGRepresentation(newImage);
    NSData * data;
    if (_globalVar.png == YES) {
        data = UIImagePNGRepresentation(newImage);
    }
    else {
        data = UIImageJPEGRepresentation(newImage, 0.5);//二次压缩
    }
    newImage = [UIImage imageWithData:data];

    return newImage;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _aLAssets.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellID = @"JCPhotoCollectionViewCell";
    __weak JCPhotoCollectionViewCell * cell = (JCPhotoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    if ([_globalVar.indexPaths containsObject:indexPath]) {
        NSInteger index = [_globalVar.indexPaths indexOfObject:indexPath];
        cell.index = index;
        cell.indexPath = indexPath;
        cell.isPicked = YES;
        [cell.button setImage:_globalVar.yesImg forState:UIControlStateNormal];
        [cell.button setTitle:[NSString stringWithFormat:@"%ld", (cell.index + 1)] forState:UIControlStateNormal];
        [cell.button setTitleEdgeInsets:UIEdgeInsetsMake(0, -(cell.button.imageView.frame.size.width / 2.0 + cell.button.titleLabel.frame.size.width / 2.0), 0, cell.button.imageView.frame.size.width / 2.0 + cell.button.titleLabel.frame.size.width / 2.0)];

    } else {
        cell.index = NSIntegerMax;
        cell.indexPath = NSIndexPathMax;
        cell.isPicked = NO;
        [cell.button setImage:_globalVar.noImg forState:UIControlStateNormal];
        [cell.button setTitle:[NSString stringWithFormat:@""] forState:UIControlStateNormal];
    }
    
    cell.selectBlock = ^(BOOL isSelect, JCPhotoCollectionViewCell *cc) {
        if (isSelect == YES) {
            
            self->_globalVar.currentNum ++;
            [self selectCompressionImageWithIndexPath:(NSIndexPath *)indexPath];

            if (self->_globalVar.currentNum  > 0) {
                self->_selectBtn.enabled = YES;
            }
            [self->_uploadButton setTitle:[NSString stringWithFormat:@"上传(%d)",self->_globalVar.currentNum] forState:UIControlStateNormal];
            NSInteger index = [self->_globalVar.indexPaths indexOfObject:indexPath];
            cell.index = index;
            cell.indexPath = indexPath;
            [cell.button setImage:[UIImage imageNamed:@"JCPhoto.bundle/y_icon_image_yes"] forState:UIControlStateNormal];
            [cell.button.layer removeAnimationForKey:@"transform.scale"];
            [cell.button.layer addAnimation:self->_globalVar.animation forKey:@"transform.scale"];
            
            if (cell.index != NSIntegerMax) {
                [cell.button setTitle:[NSString stringWithFormat:@"%ld", (cell.index + 1)] forState:UIControlStateNormal];
            } else {
                
            }
            [cell.button setTitleEdgeInsets:UIEdgeInsetsMake(0, -(cell.button.imageView.frame.size.width / 2.0 + cell.button.titleLabel.frame.size.width / 2.0), 0, cell.button.imageView.frame.size.width / 2.0 + cell.button.titleLabel.frame.size.width / 2.0)];
            
        } else if (isSelect == NO) {
            self->_globalVar.currentNum --;
            if (self->_globalVar.currentNum  == 0) {
                self->_selectBtn.enabled = NO;
            }
            if (self->_globalVar.currentNum  >= 0) {
                [self->_uploadButton setTitle:[NSString stringWithFormat:@"上传(%d)",self->_globalVar.currentNum] forState:UIControlStateNormal];
                [self deleteCompressionImageIndexPath:(NSIndexPath *)indexPath];
            }
            
            [cell.button setImage:[UIImage imageNamed:@"JCPhoto.bundle/y_icon_image_no"] forState:UIControlStateNormal];
            [cell.button setTitle:@"" forState:UIControlStateNormal];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationWhenSelectPictureName object:nil];

        }
    };
    cell.imageView.image = [UIImage imageWithCGImage:((ALAsset *)_aLAssets[indexPath.row]).thumbnail];
    
    return cell;
}

- (void)selectCompressionImageWithIndexPath:(NSIndexPath *)indexPath {

    [_globalVar.selectedAlassets addObject:_aLAssets[indexPath.row]];
    [_globalVar.indexPaths addObject:indexPath];
}

- (void)deleteCompressionImageIndexPath:(NSIndexPath *)indexPath {
    [_globalVar.selectedAlassets removeObject:_aLAssets[indexPath.row]];
    [_globalVar.indexPaths removeObject:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(2, 2, 2, 2);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellWH = ([UIScreen mainScreen].bounds.size.width - 10) / 4;
    CGSize cellSize = CGSizeMake(cellWH, cellWH);
    return cellSize;
}

//MARK: - alertViewdelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc {
    //NSLog(@"thumbnail dealloc");
}

@end
